package net.root.plain.alarm;

import java.util.ArrayList;
import java.util.List;

import net.root.plain.util.DBConn;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class AlarmDAO {
	SQLiteDatabase db = null;
	

	public AlarmDAO(SQLiteDatabase db) {
		this.db = db;
	}

	public void insertData(AlarmDTO dto) {
		ContentValues row = new ContentValues();
		row.put(DBConn.columns[1], dto.getAlarmStatus());
		row.put(DBConn.columns[2], dto.getAlarmTime());
		row.put(DBConn.columns[3], dto.getAlarmRepeat());
		row.put(DBConn.columns[4], dto.getAlarmBell());
		row.put(DBConn.columns[5], dto.getAlarmVibrate());
		row.put(DBConn.columns[6], dto.getAlarmLabel());
		db.insert(DBConn.table_name, null, row);
	}

	public List<AlarmDTO> getLists() {
		List<AlarmDTO> lists = new ArrayList<AlarmDTO>();
		AlarmDTO dto;
		Cursor cursor;
		cursor = db.query(DBConn.table_name, DBConn.columns, null, null, null,
				null, "_no asc");
		while (cursor.moveToNext()) {
			dto = new AlarmDTO();
			dto.setNo(cursor.getInt(0));
			dto.setAlarmStatus(cursor.getInt(1));
			dto.setAlarmTime(cursor.getString(2));
			dto.setAlarmRepeat(cursor.getString(3));
			dto.setAlarmBell(cursor.getString(4));
			dto.setAlarmVibrate(cursor.getInt(5));
			dto.setAlarmLabel(cursor.getString(6));
			lists.add(dto);
		}
		return lists;
	}
	
	public int getMaxNo(){
		int result = 0;
		Cursor cursor;
		cursor = db.rawQuery("select max(_no) from "+DBConn.table_name, null);
		if (cursor.moveToNext()) {
			result = cursor.getInt(0);
		}
		return result;
	}
	
	public AlarmDTO getReadData(int no){
		AlarmDTO dto = null;
		Cursor cursor;
		String selection="_no = "+no;
		cursor = db.query(DBConn.table_name, DBConn.columns, selection, null, null,
				null, "_no asc");
		if (cursor.moveToNext()) {
			dto = new AlarmDTO();
			dto.setNo(cursor.getInt(0));
			dto.setAlarmStatus(cursor.getInt(1));
			dto.setAlarmTime(cursor.getString(2));
			dto.setAlarmRepeat(cursor.getString(3));
			dto.setAlarmBell(cursor.getString(4));
			dto.setAlarmVibrate(cursor.getInt(5));
			dto.setAlarmLabel(cursor.getString(6));
		}
		return dto;
	}
	
	public void deleteData(int no){
		String whereClause="_no = "+no;
		db.delete(DBConn.table_name, whereClause, null);
	}
	
	public void updateData(AlarmDTO dto){
		ContentValues row = new ContentValues();
		row.put(DBConn.columns[1], dto.getAlarmStatus());
		row.put(DBConn.columns[2], dto.getAlarmTime());
		row.put(DBConn.columns[3], dto.getAlarmRepeat());
		row.put(DBConn.columns[4], dto.getAlarmBell());
		row.put(DBConn.columns[5], dto.getAlarmVibrate());
		row.put(DBConn.columns[6], dto.getAlarmLabel());
		String whereClause="_no = "+dto.getNo()+"";
		db.update(DBConn.table_name, row, whereClause, null);
	}
}
